﻿using DocumentFormat.OpenXml.Spreadsheet;
using SiliconSelect.BLL;
using SiliconSelect.Common;
using SiliconSelect.PlcComunication;
using SiliconSelect.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SiliconSelect.Views.UserOperatorDialog
{
    /// <summary>
    /// BoxSettings.xaml 的交互逻辑
    /// </summary>
    public partial class BoxSettings : Window
    {
        BoxSettingsViewModel viewModel = new BoxSettingsViewModel();
        public BoxSettings()
        {
            InitializeComponent();
            DataContext = viewModel;
            viewModel.RefreshModel();
        }

        private void BtnSaveClick(object sender, RoutedEventArgs e)
        {
            try
            {
                List<ushort> boxMaxCount = new List<ushort>() { 1 };
                foreach (var boxInfo in viewModel.BoxCountList)
                {
                    string queryField = "BoxNumber";
                    string queryVal = boxInfo.BoxNumber.ToString();
                    string updateField = "CountMax";
                    string updateVal = boxInfo.CountMax.ToString();
                    LocalDataAccess.UpdateBoxesStateTb(queryField, queryVal, updateField, updateVal);
                    boxMaxCount.Add((ushort)boxInfo.CountMax);
                }

                if (PlcCommunication.Instance.PlcState.IsOnline == "已连接")
                {
                    DataResult res = PlcCommunication.Instance.WriteBoxMaxNumberToPLc(boxMaxCount.ToArray());
                    if (!res.State)
                    {
                        LogHelper.WriteLog(LogType.Fatal, $"Plc通信异常,料盒最大数写入失败: {res.Message}");
                        MessageBox.Show($"Plc写入数据失败: {res.Message}", "PLC通信异常提示框", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogType.Exception, $"料盒设定失败: {ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!)}");
                MessageBox.Show($"料盒设定失败: {ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!)}", "料盒设定失败提示框", MessageBoxButton.OK, MessageBoxImage.Error);
            }
           
        }
    }
}
